cap drop _merge
drop if missing(agent_id)
sort agent year
by agent: gen experience = sum(num_list)
replace experience = experience - num_list
replace experience = 0 if experience == .
gen experience_l2 = experience - L2.experience
gen experience_l1 = experience - L.experience

by agent: gen all_experience = sum(num_bs)
replace all_experience = all_experience - num_bs
replace all_experience = 0 if all_experience == .
gen all_experience_l2 = all_experience - L2.all_experience
gen all_experience_l1 = all_experience - L.all_experience

by agent: gen experience_sale = sum(sale)
replace experience_sale = experience_sale - sale
replace experience_sale = 0 if experience_sale == .
gen experience_sale_l2 = experience_sale - L2.experience_sale
gen experience_sale_l1 = experience_sale - L.experience_sale

by agent: gen totsalary = sum(sale*close_price*.03)
replace totsalary = totsalary - sale*close_price*.03
replace totsalary = 0 if totsalary == .
gen totsalary_l2 = totsalary - L2.totsalary
replace totsalary_l2 = totsalary if year < 2005
replace totsalary = 0 if totsalary < 100
replace totsalary_l2 = 0 if totsalary_l2 < 100

gen earnings = sale2*close_price*.03 + b_num*bclose_price*.03 
egen exp_bin = cut(experience_l2), at(0,8, 28,200) icodes // the cutoff come from the full sample making each experience group have a third of listings
replace exp_bin = exp_bin+1
egen all_exp_bin = cut(all_experience_l2), at(0,14, 41,200) icodes
replace all_exp_bin = all_exp_bin+1
gen lexp_bin = L.exp_bin
gen lall_exp_bin = L.all_exp_bin
by agent: egen max_all_exp_bin = max(exp_bin)
by agent: egen max_exp_bin = max(all_exp_bin)

gen active = both>0
by agent: egen years_active = sum(active)

by agent: gen exit = 0 if active==1  & ~missing(active[_n+1]) & ~missing(active[_n+2])
by agent: replace exit = 1 if active==1  & active[_n+1]==0  & active[_n+2]==0

by agent: gen entrant = 0 if active==1 & ~missing(active[_n-1]) & ~missing(active[_n-2])
by agent: replace entrant = 1 if active==1 & active[_n-1]==0 & active[_n-2]==0 

foreach x of varlist num_list num_list_fc b_num s_num num_bs {
   cap drop `x'_cens
   gen `x'_cens = `x'
   sum `x'_cens if `x'_cens>0, d
   sum `x'_cens if `x'_cens>r(p99), d
   replace `x'_cens = . if `x' > r(p50) // 99.5th percentile
}
gen perc_seller = s_num_cens / num_bs_cens
*replace exp_bin = 0 if entrant==1

label var exit "Exit Rate"
label var num_bs_cens "Facilitated Listings"
label var s_num_cens "Listed"
label var perc_seller "Fraction Seller Agent"
label var earnings "Earnings"

gen bust = year >= 2007 & year <= 2011
gen boom = year < 2007 
gen recovery = year > 2011

label define periods 1 "2003-2006" 2 "2007-2011" 3 "2012-2013"
gen period = 1*boom + 2 * bust + 3*recovery
label values period periods

gen main_fips = lmain_fips
replace main_fips = bmain_fips if missing(lmain_fips)
